package com.summit.captureupload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Controller
public class FileUploadController {
    /*
     * 获取file.html页面
     */
    @RequestMapping("file")
    public String file(){
        return "/file";
    }

    /**
     * 实现单个文件上传
     * */
    @RequestMapping("fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("fileName") MultipartFile file){
        if(file.isEmpty()){
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = "c:/test" ;
        File dest = new File(path + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return "true";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
    }

    /*
     * 获取multifile.html页面
     */
    @RequestMapping("multifile")
    public String multifile(){
        return "/multifile";
    }

    /**
     * 实现多文件上传
     * */
    @RequestMapping(value="multifileUpload",method=RequestMethod.POST)
    public @ResponseBody String multifileUpload(HttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        List<String> uploadFileInfos=null;
        if (multipartResolver.isMultipart(request)) {
            String[] fileParams = {"fileName"};
            uploadFileInfos = uploadFile((MultipartHttpServletRequest) request, fileParams);
        }
        String ret=afterUpload(request,uploadFileInfos);
        return ret;
    }

    /**
     * 实现多个文件参数的多文件上传
     * */
    @RequestMapping(value="multiTypeFileUpload",method=RequestMethod.POST)
    public @ResponseBody String multiTypeFileUpload(HttpServletRequest request){
        //CommonsMultipartResolver依赖commons-fileupload
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        List<String> uploadFileInfos=null;
        if (multipartResolver.isMultipart(request)) {
            String[] fileParams=getFileParams();
            uploadFileInfos=uploadFile((MultipartHttpServletRequest) request,fileParams);
        }
        return afterUpload(request,uploadFileInfos);
    }

    private List<String> uploadFile(MultipartHttpServletRequest request,String[] fileParams) {
        List<String> uploadFileInfos=new ArrayList<>();
        for(String fileParam:fileParams){
            List<MultipartFile> files = request.getFiles(fileParam);
            if(files.isEmpty()){
                continue;
            }
            String path =getUploadRootPath() ;
            for(MultipartFile file:files){
                String fileName = generateDestFileName(file.getOriginalFilename());
                int size = (int) file.getSize();
                System.out.println(fileName + "-->" + size);
                if(file.isEmpty()){
                    continue;
                }else{
                    String destFilePath=path + "/" + fileName;
                    File dest = new File(destFilePath);
                    if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                        dest.getParentFile().mkdir();
                    }
                    try {
                        file.transferTo(dest);
                        uploadFileInfos.add(generateFinalFileInfo(destFilePath,fileName));
                    }catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        return uploadFileInfos;
    }

    @RequestMapping("download")
    public String downLoad(HttpServletResponse response){
        String filename="2.jpg";
        String filePath = "F:/test" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);

            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    protected String afterUpload(HttpServletRequest request,List<String> uploadFileInfos){
        Enumeration<String> paramEnum=request.getParameterNames();
        String ret="\n";
        while(paramEnum.hasMoreElements()){
            String key=paramEnum.nextElement();
            String value=request.getParameter(key);
            ret+=key+":"+value+"\n";
        }
        System.out.println(ret);
        int count=(uploadFileInfos==null)?0:uploadFileInfos.size();
        return "uploadCount:"+count+"  handle simple param result:"+ret;
    }

    /**
     * 获取目标文件名,默认返回上传文件的源文件名
     *
     * @param originalFilename
     * @return
     */
    protected String generateDestFileName(String originalFilename){
        return originalFilename;
    }

    /**
     * 获取需要存储的文件信息,默认返回目标文件名
     *
     * @param destPath       目标文件路径
     * @param destFileName   目标文件名
     * @return
     */
    protected String generateFinalFileInfo(String destPath,String destFileName){
        return destFileName;
    }

    protected String[] getFileParams(){
        String[] fileParams={"audioFileName","videoFileName","imageFileName","simpleFileName"};
        return fileParams;
    }

    protected String getUploadRootPath(){
        return "c:/test";
    }
}
